
<?php

class Data
{

    private $file = 'data.json';

    private function getDataFromDb()
    {
        $mysqli = new \mysqli('127.0.0.1', '用户', '密码', 'city', '3306');
        $result = $mysqli->query('select * from city_data');
        $data = $result->fetch_all(MYSQLI_ASSOC);
        if ($data) {
            // Set into cache.
            $this->cacheData($data);
        }
        $mysqli->close();
        return $data;
    }

    private function cacheData($data)
    {
        return file_put_contents($this->file, json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
    }

    public function getData()
    {
        $data = [];
        // read data from cache.
        is_file($this->file) && $data = json_decode(file_get_contents($this->file), true);
        if (!$data) {
            // read data from db.
            return $this->getDataFromDb();
        }
        return $data;
    }
}
